﻿goog.provide('imc.ui.RolPage');
//goog.inherits(imc.ui.RolPage, imc.ui.Page);

imc.ui.RolPage = function (opt) { //Constructor
    //attributes privados
    var dataGrid;

    /*\\Behavior : --------------------------------- */
    //Todos los ids van con #
    this.opt={
        idDivContent:"#der"
        ,idDivNav:"#izq"
        , idTableDataTable: "#tblDatosRoles"
        ,uriSrvGetDataListRol:"Services/User.svc/GetDataListRol"
        ,uriSrvDeleteRol:"Services/User.svc/DeleteRol"
        ,uriSrvInsertRol:"Services/User.svc/InsertRol"
        ,uriSrvUpdateRol:"Services/User.svc/UpdateRol"
        ,uriSrvGetOneRol:"Services/User.svc/GetOneRol"
    };

    $().extend(this.opt,opt);
    this.draw();
    /*//Behavior : ------------------------------- */
}//Fin constructor

//Atributos Público************************************************
imc.ui.RolPage.prototype.oTableTblRoles = null;
imc.ui.RolPage.prototype.opt = null;
imc.ui.RolPage.prototype.id_New_Rol = "";

//Metodos Públicos*************************************************
imc.ui.RolPage.prototype.draw = function () {
    $(this.opt.idDivNav).load('rolPage.html #navigationPanelRoles', function () { });
    this.loadContent();
};

imc.ui.RolPage.prototype.loadContent = function () {
    var that = this;
    $(this.opt.idDivContent).load('rolPage.html #rolesContent', function () {
        that.rolDataTable();
    });
}

imc.ui.RolPage.prototype.rolDataTable = function () {
    var that = this;
    $.ajax({
        url: "Services/User.svc/GetDataListRol"
        ,type: "POST"
        ,dataType: "json"
        ,data: '{}'
        ,contentType: "application/json; charset=utf-8"
        ,success: function (data) {
            oTableTblRoles = $('#tblDatosRoles').dataTable({
                'bInfo': false
                ,'bPaginate': false
                ,'bLengthChange': false
                ,'bRetrieve': true, 'sDom': ''
                ,'sInfoEmpty': ''
                ,'bAutoWidth': false
                ,aaData: data.GetDataListRolResult
                ,aoColumns: [
                    {
                        "aTargets": [0]
                        ,"fnRender": function (oObj) {
                            return '<input type="checkbox" id="readonly" imc-data="' + oObj.aData["ID_ROL"] + '" value="' + oObj.aData[0] + '" name="check" />';
                        }
                        ,"sClass": "checkboxId"
                        ,"bSearchable": false
                        ,"bSortable": false
                        ,"mDataProp": "check"
                        ,"sWidth": "4%"
                    }
                    ,{ "sTitle": "Nombre", "mDataProp": "ROL_NAME", "sClass": "editarRol" }
                    ,{ "sTitle": "Prioridad", "mDataProp": "ROL_PRIORITY", "sClass": "editarRol" }
                ]
            });
            $('#tblDatosRoles tbody .editarRol').die('click');
            $('#tblDatosRoles tbody .editarRol').live('click', function () {
                var oTableTblRoles = $('#tblDatosRoles').dataTable();
                var sDataRol = oTableTblRoles.fnGetData($(this).parent().get(0));
                console.log(sDataRol);
                for (var i in sDataRol) {
                    if (i = 'ID_ROL') {
                        idRol = sDataRol[i];
                    }
                }
                var dlg = that.dlgUpdateRol(idRol);
                dlg.setVisible(true);
                //Recuperar campos para modificar
                $.ajax({
                    type: "POST"
                    ,url: that.opt.uriSrvGetOneRol
                    ,data: '{"ID_ROL":' + idRol + '}'
                    ,contentType: "application/json; charset=utf-8"
                    ,dataType: "json"
                    ,success: function (data) {
                        if (data.GetOneRolResult != null) {
                            /*\\Object CharCounter : ------------------------*/
                            var userCharCounter = new imc.CharCounter({columnName:"ROL"});
                            /*//Object CharCounter : ------------------------*/
                            document.getElementById('ROL_NAME').value = data.GetOneRolResult["ROL_NAME"];
                            document.getElementById('ROL_PRIORITY').value = data.GetOneRolResult["ROL_PRIORITY"];
                        } else {
                            alert('Los datos vienen vacios ({"GetOneRolResult":null})');
                        }
                    }
                    ,error: function (result) {
                        alert('Error al recuperar roles ' + result.status + ' ' + result.statusText);
                    }
                });
            });
            $('#nuevoRol').die('click');
            $('#nuevoRol').live('click', function () {
                var dlg = that.dlgNewRol();
                dlg.setVisible(true);
                /*\\Object CharCounter : ------------------------*/
                var userCharCounter = new imc.CharCounter({columnName:"ROL"});
                /*//Object CharCounter : ------------------------*/
            });
            $('#eliminarRol').die('click');
            $('#eliminarRol').live('click', function () {
                var oTableTblRoles = $('#tblDatosRoles').dataTable();
                var stringDeleteRol = "";
                $('input[type="checkbox"]:checked', oTableTblRoles.fnGetNodes()).each(function (i) {
                    stringDeleteRol += $(this).attr("imc-data") + ",";
                });
                if (stringDeleteRol != "") {
                    stringDeleteRol = stringDeleteRol.substring(0, stringDeleteRol.length - 1);
                }
                if (stringDeleteRol != "") {
                    var dlg = that.dlgDeleteRol(stringDeleteRol);
                    dlg.setVisible(true);
                } else {
                    alert('No hay ningún rol seleccionado');
                    return true;
                }
            });
        },
        error: function (result) {
            alert('Error al mostrar el grid roles ' + result.status + ' ' + result.statusText);
        }
    });
};

    imc.ui.RolPage.prototype.reloadRolDataTable = function () { //Recargar tabla al agregar, modificar o eliminar rol
        var that = this;
        $.ajax({
            type: "POST"
            ,url: this.opt.uriSrvGetDataListRol
            ,data: '{}'
            ,contentType: "application/json; charset=utf-8"
            ,dataType: "json"
            ,success: function (data) {
                var ot = $("#tblDatosRoles").dataTable();
                ot.fnClearTable();
                ot.fnAddData(data.GetDataListRolResult);
                for (var i = 0; i < data.GetDataListRolResult.length; i++) {
                    that.opt.id_New_Rol = data.GetDataListRolResult[i].ID_ROL;
                }
                console.log('Al recargar: '+that.opt.id_New_Rol);
            }
            ,error: function (result) {
                alert('Error al recargar la tabla de roles ' + result.status + ' ' + result.statusText);
            }
        });
    }; //Fin recargar tabla al agregar, modificar o eliminar rol

imc.ui.RolPage.prototype.dlgNewRol = function () { //Dialog agregar rol
    var that = this;
    this.dialogAgregarRol = new goog.ui.Dialog();
    this.dialogAgregarRol.setContent(
        '<div style="font-size: 85%;">' +
            +'<label id="validarAgregarRol"></label><br /><br />'
            +'<div><div style="width:150px; float:left;"><label style="float:right;">Nombre: </label></div><div style="width:450px; float:left;"><input type="text" id="ROL_NAME" style="width: 250px;" /></div></div><br /><br />'
            +'<div><div style="width:150px; float:left;"><label style="float:right;">Prioridad: </label></div><div style="width:450px; float:left;"><input type="text" id="ROL_PRIORITY" style="width: 250px;" /></div></div>'
        +'</div><br /><br />'
    );
    var titleAgregarRol = goog.dom.createDom("p", { style: 'margin:0;padding:0;color:black;font-size:80%;' }, 'Agregar Rol');
    this.dialogAgregarRol.setTitle(titleAgregarRol);
    var btnAgregarRol = new goog.ui.Dialog.ButtonSet();
    btnAgregarRol.addButton({ caption: "Agregar", key: "e" }).addButton({ caption: "Cancelar", key: "o" });
    this.dialogAgregarRol.setButtonSet(btnAgregarRol);
    this.dialogAgregarRol.setDisposeOnHide(true);
    goog.events.listen(this.dialogAgregarRol, goog.ui.Dialog.EventType.SELECT, function (e) {
        if (e.key == "o") {
            return true;
        } else {
            var val2 = $("#ROL_NAME").val();
            var val3 = $("#ROL_PRIORITY").val();
            if (val2 == "" || val3 == "") {
                $('#validarAgregarRol').css({ color: "Red" });
                $('#validarAgregarRol').html('Todos los campos son requeridos');
                return false;
            }
            else if (!/^([0-9])*$/.test(val3)) {
                $("#prioridadRol").css({ background: "#FFFF66" });
                $('#validarAgregarRol').css({ color: "Red" });
                $('#validarAgregarRol').html('La prioridad solo puede ser numérica');
                return false;
            } else {
                $.ajax({
                    url: that.opt.uriSrvInsertRol
                    ,type: "POST"
                    ,data: '{"ROL_NAME":"' + val2 + '","ROL_PRIORITY":' + val3 + '}'
                    ,contentType: "application/json; charset=utf-8"
                    ,dataType: "json"
                    ,success: function (data) {
                        var test = "";
                        test = data.InsertRolResult.state;
                        console.log('state: '+test);
                        if(!test){
                            console.log("entro dlgNuevo")    ;
                            $("#nombreRol").css({ background: "#FFFF66" });
                            $("#nombreRol").css({ color: "red" });
                            $('#validarAgregarRol').css({ color: "Red" });
                            $('#validarAgregarRol').html('Ya existe un rol con este nombre');
                            return null;
                        } else {
                            that.reloadRolDataTable();
                            that.dialogAgregarRol.setVisible(false);
                        }
                    }
                    ,error: function (result) {
                        alert('Error al agregar rol ' + result.status + ' ' + result.statusText);
                    }
                });
                return false;
            }
        }
    });
    return this.dialogAgregarRol;
};  //Fin dialog agregar Rol

imc.ui.RolPage.prototype.dlgDeleteRol = function (stringDeleteRol) { //Dialog borrar Roles
    var that = this;
    this.dialogBorrarRol = new goog.ui.Dialog();
    this.dialogBorrarRol.setContent(
        '<div style="font-size: 85%;">'
            +'<label>¿Está seguro que desea eliminar los Roles seleccionados?</label><br />'
            +'<label>Si elimina un Rol se eliminara también todas las referencias que tenga un Usario con este.</label><br />'
        +'</div>'
    );
    this.dialogBorrarRol.setTitle('Borrar Rol');
    var btnBorrarRol = new goog.ui.Dialog.ButtonSet();
    btnBorrarRol.addButton({ caption: "Borrar", key: "e" }).addButton({ caption: "Cancelar", key: "o" });
    this.dialogBorrarRol.setButtonSet(btnBorrarRol);
    this.dialogBorrarRol.setDisposeOnHide(true);
    goog.events.listen(this.dialogBorrarRol, goog.ui.Dialog.EventType.SELECT, function (e) {
        if (e.key == "o") {
            return true;
        } else {
            console.log(stringDeleteRol);
            $.ajax({
                url: "Services/User.svc/DeleteRol",
                type: "POST",
                dataType: "json",
                data: '{"ID_ROL": "' + stringDeleteRol + '" }',
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    if (data) {
                        console.log(data.DeleteRolResult);
                        that.reloadRolDataTable();
                        //alert(that.opt.id_New_Rol);
                        return true;
                    }
                },
                error: function (result) {
                    alert('Error al borrar roles ' + result.status + ' ' + result.statusText);
                }
            });
        }
    });
    return this.dialogBorrarRol;
}   //Fin dialog borrar roles

imc.ui.RolPage.prototype.dlgUpdateRol = function (idRol) { //Dialog modificar rol
    var that = this;
    this.dialogModificarRol = new goog.ui.Dialog();
    this.dialogModificarRol.setContent(
        '<div style="font-size: 85%;"><label id="validarModificarRol"></label><br /><br />' +
            '<div><div style="width:150px; float:left;"><label style="float:right;">Nombre: </label></div><div style="width:450px; float:left;"><input type="text" id="ROL_NAME" style="width: 250px;" /></div></div><br /><br />' +
            '<div><div style="width:150px; float:left;"><label style="float:right;">Prioridad: </label></div><div style="width:450px; float:left;"><input type="text" id="ROL_PRIORITY" style="width: 250px;" /></div></div></div><br /><br />'
    );
    var titleModificarRol = goog.dom.createDom("p", { style: 'margin:0;padding:0;color:black;font-size:80%;' }, 'Modificar Rol');
    this.dialogModificarRol.setTitle(titleModificarRol);
    var btnModificarRol = new goog.ui.Dialog.ButtonSet();
    btnModificarRol.addButton({ caption: "Guardar cambios", key: "e" }).addButton({ caption: "Cancelar", key: "o" });
    this.dialogModificarRol.setButtonSet(btnModificarRol);
    this.dialogModificarRol.setDisposeOnHide(true);
    goog.events.listen(this.dialogModificarRol, goog.ui.Dialog.EventType.SELECT, function (e) {
        //alert(e.key);
        if (e.key == "o") {
            return true;
        } else {
            var val1 = $("#ROL_NAME").val();
            var val2 = $("#ROL_PRIORITY").val();
            if (val1 == "" || val2 == "") {
                $('#validarModificarRol').css({ color: "Red" });
                $('#validarModificarRol').html('Todos los campos son requeridos');
                return false;
            }
            else if (!/^([0-9])*$/.test(val2)) {
                $("#prioridadRolA").css({ background: "#FFFF66" });
                $('#validarModificarRol').css({ color: "Red" });
                $('#validarModificarRol').html('La prioridad solo puede ser numérica');
                return false;
            } else {
                $.ajax({
                    url: "Services/User.svc/UpdateRol"
                    ,type: "POST"
                    ,data: '{"ID_ROL":' + idRol + ',"ROL_NAME":"' + val1 + '","ROL_PRIORITY":' + val2 + '}'
                    ,contentType: "application/json; charset=utf-8"
                    ,dataType: "json"
                    ,success: function (data) {
                        that.reloadRolDataTable();
                        return true;
                    }
                    ,error: function (result) {
                        alert('Error al modificar rol' + result.status + ' ' + result.statusText);
                    }
                });
            }
        }
    });
    return this.dialogModificarRol;
}    //Fin dialog modificar rol

imc.ui.RolPage.prototype.clickBtnNewRol = function () {
};

imc.ui.RolPage.prototype.clickBtnDeleteRol = function () {
};

imc.ui.RolPage.prototype.clickBtnRow = function () {
};